// main.js
const { app, BrowserWindow, Menu } = require('electron')

app.disableHardwareAcceleration()

function createWindow() {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: `${__dirname}/preload.js`,
      nodeIntegration: true,
      contextIsolation: false,
      enableRemoteModule: false,
      webSecurity: false,
      webviewTag: false,
      disableHardwareAcceleration: true // 这仍然是必要的
    }
  })

  win.loadFile('dist/index.html')
}

// MacOS 自定义菜单
function setupMacMenu() {
  if (process.platform === 'darwin') {
    const menu = Menu.buildFromTemplate([
      {
        label: 'Application',
        submenu: [
          { label: 'About Application', selector: 'orderFrontStandardAboutPanel:' },
          { type: 'separator' },
          { label: 'Services', submenu: [] },
          { type: 'separator' },
          { label: 'Hide Application', accelerator: 'Command+H', selector: 'hide:' },
          {
            label: 'Hide Others',
            accelerator: 'Command+Shift+H',
            selector: 'hideOtherApplications:'
          },
          { label: 'Show All', selector: 'unhideAllApplications:' },
          { type: 'separator' },
          { label: 'Quit Application', accelerator: 'Command+Q', click: () => app.quit() }
        ]
      },
      {
        label: 'Edit',
        submenu: [
          { label: 'Undo', accelerator: 'Command+Z', selector: 'undo:' },
          { label: 'Redo', accelerator: 'Shift+Command+Z', selector: 'redo:' },
          { type: 'separator' },
          { label: 'Cut', accelerator: 'Command+X', selector: 'cut:' },
          { label: 'Copy', accelerator: 'Command+C', selector: 'copy:' },
          { label: 'Paste', accelerator: 'Command+V', selector: 'paste:' },
          { label: 'Select All', accelerator: 'Command+A', selector: 'selectAll:' }
        ]
      }
    ])

    Menu.setApplicationMenu(menu)
  }
}

app.whenReady().then(() => {
  setupMacMenu()
  createWindow()

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })

  // Implement the applicationSupportsSecureRestorableState: method.
  app.on('browser-window-created', (event, window) => {
    window.webContents.on('did-finish-load', () => {
      window.webContents.executeJavaScript(`
        if (typeof NSApplication !== 'undefined' && typeof NSApplication.sharedApplication !== 'undefined') {
          NSApplication.sharedApplication.delegate.applicationSupportsSecureRestorableState = function() {
            return true;
          };
        }
      `)
    })
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit()
})
